/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package th.stripes.action;

import able.stripes.JSP;
import com.google.inject.Inject;
import com.oas.thit._this.taha.xsd.TaHaProfileBody;
import com.oas.thit._this.taha.xsd.TaHaRegistrationRequestBody;
import com.oas.thit._this.taha.xsd.TaHaSchoolBody;
import com.oas.thit._this.taha.xsd.TaHaUniversityBody;
import com.oas.thit._this.xsd.THISBaseDataElementBody;
import com.oas.thit.xmlmessage.xsd.Header;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.xml.bind.JAXBElement;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.HttpCache;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.action.Wizard;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import th.dao.KodFakultiDAO;
import th.dao.KodJantinaDAO;
import th.dao.KodJenisPengajianDAO;
import th.dao.KodJenisSekolahDAO;
import th.dao.KodNegeriDAO;
import th.dao.KodPengajianDAO;
import th.dao.KodSekolahDAO;
import th.dao.KodTahapPengajianDAO;
import th.dao.KodUniversitiDAO;
import th.dao.PoskodDAO;
import th.manager.ResponseManager;
import th.manager.TaHaManager;
import th.model.KodJantina;
import th.model.KodSekolah;
import th.model.Poskod;
import th.model.Taha;
import th.stripes.BaseActionBean;
import th.stripes.util.DateConverter;
import th.stripes.util.DateFormatDetector;
import th.stripes.util.ListUtil;
import th.stripes.util.Util;
import th.stripes.webservice.WebServiceUtil;

/**
 *
 * @author fikri
 */
@HttpCache(allow = false)
@Wizard(startEvents = "TahaReg_Step1")
@UrlBinding("/taha/register")
public class TaHaRegistrationAction extends BaseActionBean {

    @ValidateNestedProperties({ 
        @Validate(field="trhmasukIPT", converter=DateConverter.class),
        @Validate(field="trhtamatIPT", converter=DateConverter.class)
    }) 
    private Taha taha;
    private static String SUCCESSFUL = "0000";
    private static String SYSTEM_ERROR = "9999";
    private static String UNREGISTERED_TAHA = "5800";
    private static String TAHA_ENQ_MSG_ID = "TPTAPRQRWD01";
    private static String TAHA_REG_MSG_ID = "TPTAPRUPWD01";
    private static String HEADER_ID_TAHA_ENQUIRY = "THSTAQR";
    private static String HEADER_ID_TAHA_REGISTER = "THSTAUP";
    private List<KodSekolah> senaraiSekolah;
    @Inject
    private Util util;
    @Inject
    private ListUtil listUtil;
    @Inject
    private WebServiceUtil webUtil;
    @Inject
    private KodJantinaDAO kodJantinaDAO;
    @Inject
    private KodNegeriDAO kodNegeriDAO;
    @Inject
    private ResponseManager responseManager;
    @Inject
    private KodUniversitiDAO kodUniversitiDAO;
    @Inject
    private KodJenisPengajianDAO kodJenisPengajianDAO;
    @Inject
    private KodTahapPengajianDAO kodTahapPengajianDAO;    
    @Inject 
    private PoskodDAO poskodDAO;
    @Inject
    private TaHaManager tahaManager;
    
    @Inject
    private KodSekolahDAO kodSekolahDAO;
    @Inject
    private KodJenisSekolahDAO kodJenisSekolahDAO;
    @Inject
    private KodFakultiDAO kodFakultiDAO;
    @Inject
    private KodPengajianDAO kodPengajianDAO;
    
    private com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
    private com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap11Endpoint();
    
    private static Logger LOG = Logger.getLogger(TaHaRegistrationAction.class);

    @DefaultHandler
    @HandlesEvent("TahaReg_Step1")
    public Resolution showFormSemak() {
        return new JSP("taha/pendaftaran_taha_main.jsp");
    }

    @HandlesEvent("TahaReg_Step2")
    public Resolution queryAccTH() {
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

        String responseCode = "";

        try { // Call Web Service Operation

            // TODO initialize WS operation arguments here
            com.oas.thit._this.xsd.THISRequest req = new com.oas.thit._this.xsd.THISRequest();
            // TODO process result here
            com.oas.thit._this.xsd.ObjectFactory objFactory = new com.oas.thit._this.xsd.ObjectFactory();
            com.oas.thit.xmlmessage.xsd.ObjectFactory objHeader = new com.oas.thit.xmlmessage.xsd.ObjectFactory();
            Header reqHead = objHeader.createHeader();
            reqHead.setMsgId(objHeader.createHeaderMsgId(TAHA_ENQ_MSG_ID));
            reqHead.setResponseCode(objHeader.createHeaderResponseCode(SUCCESSFUL));

            reqHead.setTxid(objHeader.createHeaderTxid(webUtil.getHeaderID(TAHA_ENQ_MSG_ID, HEADER_ID_TAHA_ENQUIRY)));

            THISBaseDataElementBody reqBody = objFactory.createTHISBaseDataElementBody();
            reqBody.setTHAcct(objFactory.createTHISBaseDataElementBodyTHAcct(taha.getNoAkaun()));
            reqBody.setTHICNo(objFactory.createTHISBaseDataElementBodyTHICNo(taha.getNoPengenalan()));

            JAXBElement<THISBaseDataElementBody> jReqBody = objFactory.createTHISRequestBody(reqBody);
            req.setBody(jReqBody);

            JAXBElement<Header> jReqHead = objHeader.createEventHeader(reqHead);
            req.setHeader(jReqHead);
            // TODO process result here
            com.oas.thit._this.taha.xsd.TaHaProfileQueryResponse result = port.tahaProfileQuery(req);

            Header header = result.getHeader().getValue();
            responseCode = header.getResponseCode().getValue();
            if (responseCode.equals(SUCCESSFUL)) {
                //utk pendaftaran taha , kod 0000 ada 2 kemungkinan.
                //1. 0000 - telah berdaftar
                //2. 0000 - pendaftaran telah berjaya
//                addSimpleError("" + responseManager.getResponseMessage(responseCode, TAHA_ENQ_MSG_ID));
                addSimpleError("AKAUN TELAH BERDAFTAR DENGAN KELAB TAHA/TAHA@U. SILA HUBUNGI THCC DI TALIAN 03-62071919.");
                return new JSP("taha/msg.jsp");
            }else if (responseCode.equals(UNREGISTERED_TAHA)) { 
                
                TaHaProfileBody resp = result.getBody().getValue();
                taha.setNoAkaun(resp.getTHAcct().getValue());
                taha.setNama(resp.getTHName().getValue());
                taha.setNoPengenalan(resp.getTHICNo().getValue());
                if (StringUtils.isNotBlank(resp.getTHDOB().getValue())) {
                    String df = new DateFormatDetector().getDateFormat(resp.getTHDOB().getValue());
                    sdf = new SimpleDateFormat(df);
                    taha.setTrhLahir(sdf.parse(resp.getTHDOB().getValue()));
                    Date today = new Date();
                    int age = util.getAge(resp.getTHDOB().getValue(), sdf.format(today), df);
                    taha.setUmur(age);
                    if (age < 17) {
                        taha.setJenisKelab("TaHa");
                    } else {
                        taha.setJenisKelab("TaHa@U");
                    }
                    if (age < 7) {
                        addSimpleError("Umur dibawah 7 tahun tidak dibenarkan mendaftar.");
                        return new JSP("taha/msg.jsp");
                    }
                }                
               
                if(resp.getTHGender().getValue()!=null)
                    taha.setJantina(kodJantinaDAO.findById(resp.getTHGender().getValue().trim()));
                if(resp.getTHAddress1().getValue()!=null)
                    taha.setAlamat1(resp.getTHAddress1().getValue().trim());
                if(resp.getTHAddress2().getValue()!=null)
                    taha.setAlamat2(resp.getTHAddress2().getValue().trim());
                if(resp.getTHAddress3().getValue()!=null)
                    taha.setAlamat3(resp.getTHAddress3().getValue().trim());
                
                taha.setAlamat4("");
                if(resp.getTHPoskod().getValue()!=null){
                    Poskod poskod = poskodDAO.findById(resp.getTHPoskod().getValue().trim());
                    taha.setPoskod(poskod);
                }                    
                if(resp.getTHState().getValue()!=null)
                    taha.setNegeri(kodNegeriDAO.findById(resp.getTHState().getValue().trim()));
                if(resp.getTHPhone().getValue()!=null)
                    taha.setTelefon(resp.getTHPhone().getValue().trim());
                if(resp.getTHemail().getValue()!=null)
                    taha.setEmail(resp.getTHemail().getValue().trim());      
                
                if (taha.getTrhmasukIPT() != null) {
                    sdf = new SimpleDateFormat("dd/MM/yyyy");
                    String d1 = sdf.format(taha.getTrhmasukIPT());
                    LOG.debug("tarikh masuk :" + d1);
                    taha.setTrhmasukIPT( sdf.parse(d1) );
                }
                
                
                LOG.debug("tarikh masuk :" + taha.getTrhmasukIPT());
                LOG.debug("tarikh tamat :" + taha.getTrhtamatIPT());                
                
                return new JSP("taha/pendaftaran_taha.jsp");
            }else{
                addSimpleError(responseManager.getResponseMessage(responseCode, TAHA_ENQ_MSG_ID));
            }
        } catch (Exception ex) {
            LOG.error(ex);
            addSimpleError(ex.getMessage());  
        }        
        return new JSP("taha/msg.jsp");
    }
    
    @HandlesEvent("TahaReg_Step3a")
    public Resolution showConfirmation() {
        
        if ( StringUtils.isNotBlank(taha.getJantina().getKod()) ) {
            KodJantina jantina = kodJantinaDAO.findById(taha.getJantina().getKod());
            taha.setJantina(jantina);
         }
        
        if (StringUtils.isNotBlank(taha.getNegeri().getCode())) {
            taha.setNegeri( kodNegeriDAO.findById(taha.getNegeri().getCode()));
        }
        
        if (taha.getUmur() < 17){
            
            if (StringUtils.isNotBlank(taha.getSekolah().getKod())) {
                taha.setSekolah( kodSekolahDAO.findById(taha.getSekolah().getKod()));
            }
            
            if (StringUtils.isNotBlank(taha.getJenisSekolah().getKod())) {
                taha.setJenisSekolah( kodJenisSekolahDAO.findById(taha.getJenisSekolah().getKod()));
            }
            
            if (StringUtils.isNotBlank(taha.getNegeriSekolah().getCode())) {
                taha.setNegeriSekolah( kodNegeriDAO.findById(taha.getNegeriSekolah().getCode()));
            }            
            
        } else {
            
            taha.setFakultiPengajian(kodFakultiDAO.findById(taha.getFakultiPengajian().getKod()));
            taha.setTahapPengajian( kodTahapPengajianDAO.findById(taha.getTahapPengajian().getKod()));
            taha.setUniversiti(kodUniversitiDAO.findById(taha.getUniversiti().getKod()));
            taha.setJenisPengajian( kodJenisPengajianDAO.findById(taha.getJenisPengajian().getKod()) );
            taha.setJurusanPengajian(kodPengajianDAO.findById(taha.getJurusanPengajian().getKod()));           
            
        }
        
        return new JSP("taha/registration_confirmation.jsp");        
    }

    @HandlesEvent("TahaReg_Step3")
    public Resolution registerTaHa() {
        //todo invoke web service
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String responseCode = "";
        try {     
            // TODO initialize WS operation arguments here
            com.oas.thit._this.taha.xsd.TaHaRegistrationRequest req = new com.oas.thit._this.taha.xsd.TaHaRegistrationRequest();
            //create body here            
            com.oas.thit._this.xsd.ObjectFactory baseObj = new com.oas.thit._this.xsd.ObjectFactory();
            com.oas.thit._this.taha.xsd.ObjectFactory obj = new com.oas.thit._this.taha.xsd.ObjectFactory();
            TaHaRegistrationRequestBody reqBody = obj.createTaHaRegistrationRequestBody();            
            reqBody.setTHAcct(baseObj.createTHISBaseDataElementBodyTHAcct(taha.getNoAkaun().trim()));
            reqBody.setTHICNo(baseObj.createTHISBaseDataElementBodyTHICNo(taha.getNoPengenalan().trim()));
            reqBody.setTHAddress1(baseObj.createTHProfileRequestBodyTHAddress1(taha.getAlamat1().trim()));
            reqBody.setTHAddress2(baseObj.createTHProfileRequestBodyTHAddress2(taha.getAlamat2().trim()));
            reqBody.setTHAddress3(baseObj.createTHProfileRequestBodyTHAddress3(StringUtils.isBlank(taha.getAlamat3()) ? "" :  taha.getAlamat3().trim()));
            reqBody.setTHPoskod(baseObj.createTHProfileRequestBodyTHPoskod(taha.getPoskod().getPoskod()));
            if(taha.getNegeri()!=null) {
                reqBody.setTHState(baseObj.createTHProfileRequestBodyTHState(taha.getNegeri().getCode()));
            }
            reqBody.setTHDOB(obj.createTaHaProfileBodyTHDOB(sdf.format(taha.getTrhLahir())));            
            if(taha.getJantina()!=null) {
                reqBody.setTHGender(obj.createTaHaProfileBodyTHGender(taha.getJantina().getKod()));
            }
            reqBody.setTHName(obj.createTaHaProfileBodyTHName(taha.getNama().trim()));
            reqBody.setTHPhone(obj.createTaHaProfileBodyTHPhone( StringUtils.isBlank(taha.getTelefon()) ? "" :  taha.getTelefon().trim()));
            reqBody.setTHemail(obj.createTaHaProfileBodyTHemail( StringUtils.isBlank(taha.getEmail()) ? "" :  taha.getEmail().trim()));
            reqBody.setTHAge( obj.createTaHaRegistrationRequestBodyTHAge( String.valueOf(taha.getUmur())) );
            reqBody.setTHClubType( obj.createTaHaRegistrationRequestBodyTHClubType( taha.getJenisKelab()));

            if (taha.getUmur() < 17) {
                TaHaSchoolBody reqSchoolBody = obj.createTaHaSchoolBody();
                reqSchoolBody.setTHSchool(obj.createTaHaSchoolBodyTHSchool( StringUtils.isBlank(taha.getSekolah().getKod()) ? "" :  taha.getSekolah().getKod()));
                reqSchoolBody.setTHSchoolCat(obj.createTaHaSchoolBodyTHSchoolCat(StringUtils.isBlank(taha.getJenisSekolah().getKod()) ? "" :  taha.getJenisSekolah().getKod()));
                reqSchoolBody.setTHSchoolState(obj.createTaHaSchoolBodyTHSchoolState(
                        StringUtils.isBlank(taha.getNegeriSekolah().getCode()) ? "" :  taha.getNegeriSekolah().getCode()));
//                JAXBElement<TaHaSchoolBody> jSchoolBody = obj.createTaHaProfileBodyUnder18(reqSchoolBody);
                reqBody.getSubElement1().add(reqSchoolBody);
            } else {
                TaHaUniversityBody reqUniBody = obj.createTaHaUniversityBody();
                reqUniBody.setTHFaculty(obj.createTaHaUniversityBodyTHFaculty(
                        StringUtils.isBlank(taha.getFakultiPengajian().getKod()) ? "" :  taha.getFakultiPengajian().getKod()));
                reqUniBody.setTHMatrik(obj.createTaHaUniversityBodyTHMatrik(
                        StringUtils.isBlank(taha.getNoMatrik()) ? "" :  taha.getNoMatrik()));
                reqUniBody.setTHUniversity(obj.createTaHaUniversityBodyTHUniversity(
                        StringUtils.isBlank(taha.getUniversiti().getKod()) ? "" :  taha.getUniversiti().getKod()));
                reqUniBody.setTHLevel(obj.createTaHaUniversityBodyTHLevel(
                        StringUtils.isBlank(taha.getTahapPengajian().getKod()) ? "" :  taha.getTahapPengajian().getKod()));
                reqUniBody.setTHProgramtype(obj.createTaHaUniversityBodyTHProgramtype(
                        StringUtils.isBlank(taha.getJenisPengajian().getKod()) ? "" :  taha.getJenisPengajian().getKod()));
                reqUniBody.setTHAcademicStream( obj.createTaHaUniversityBodyTHAcademicStream( 
                        StringUtils.isBlank(taha.getJurusanPengajian().getKod()) ? "" :  taha.getJurusanPengajian().getKod()));
                sdf = new SimpleDateFormat("yyyyMMdd");
                if (taha.getTrhmasukIPT() != null){
                    reqUniBody.setTHAdmissionDate(obj.createTaHaUniversityBodyTHAdmissionDate(sdf.format(taha.getTrhmasukIPT())));
                } else {
                    reqUniBody.setTHAdmissionDate(obj.createTaHaUniversityBodyTHAdmissionDate(""));
                }
                sdf = new SimpleDateFormat("yyyyMM");
                if (taha.getTrhtamatIPT() != null){
                    reqUniBody.setTHGradYear(obj.createTaHaUniversityBodyTHGradYear(sdf.format(taha.getTrhtamatIPT())));             
                }else {
                    reqUniBody.setTHGradYear(obj.createTaHaUniversityBodyTHGradYear(""));             
                }
                reqBody.getSubElement2().add(reqUniBody);
            }
            
            
            //setting up req            
            req.setHeader(webUtil.createHeader(TAHA_REG_MSG_ID, HEADER_ID_TAHA_REGISTER));
            JAXBElement<TaHaRegistrationRequestBody> jReqBody = obj.createTaHaRegistrationRequestBody(reqBody);
            req.setBody(jReqBody);

            // TODO process result here
            com.oas.thit._this.xsd.THISResponse result = port.tahaRegistration(req);
            Header header = result.getHeader().getValue();
            responseCode = header.getResponseCode().getValue();

            if (responseCode.equals(SUCCESSFUL)) {                 
                tahaManager.saveTaHa(taha);
                addSimpleMessage( responseManager.getResponseMessage(responseCode, TAHA_REG_MSG_ID));
            } else {
                addSimpleError(responseManager.getResponseMessage(responseCode, TAHA_REG_MSG_ID)); 
            }

        } catch (Exception ex) {
//            responseCode = SYSTEM_ERROR;            
            addSimpleError(ex.getMessage()); 
            LOG.error(ex);
        }          
        return new JSP("taha/msg.jsp");
    }

    public Taha getTaha() {
        return taha;
    }

    public void setTaha(Taha taha) {
        this.taha = taha;
    }
}
